<template>
  <div>
    <el-row>
      <el-col :span="24">
        <el-input placeholder="请选择" v-model="grid" v-if="vlistEntity.vlistType!=2" disabled>
          <el-button slot="append" @click="queryClick">...</el-button>
        </el-input>
        <!-- 下拉框 -->
        <el-select clearable v-model="selectValue" v-if="vlistEntity.vlistType==2" @change="selectChange">
          <el-option v-for="item in selectData" :label="item.LABEL" :value="item.ID" :key="item.ID"></el-option>
        </el-select>


        <el-dialog title="值列表" :visible.sync="displayGrid" width="60%">
          <el-input
            v-if="vlistEntity.vlistType!=2"
            size="medium"
            placeholder="请输入查询条件"
            v-model="vlistQueryCondtion"
            @input="queryListData"
          ></el-input>
          <div class="panel paneldefault vlist-dialog">
            <div class="panelheading">
              <span v-if="vlistEntity.vlistType==0" class="paneltitle">值列表选择</span>
              <span v-if="vlistEntity.vlistType==1" class="paneltitle">树列表选择</span>
            </div>
            <div class="panelbody">
              <!-- 单选 -->
              <el-table
                v-if="vlistEntity.vlistType==0 && vlistEntity.vlistMode==0"
                ref="vlistTable00"
                highlight-current-row
                stripe
                :data="tableData.filter(data => !vlistQueryCondtion || data[this.tableColumn[0].id].toLowerCase().includes(vlistQueryCondtion.toLowerCase()))"
                border
                height="250"
                style="width: 100%"
                v-loading="loading"
                element-loading-text="拼命加载中"
                element-loading-spinner="el-icon-loading"
                element-loading-background="rgba(0, 0, 0, 0.8)"
                @row-click="handleRowClick"
              >
                <el-table-column
                  v-for="item in tableColumn"
                  :key="item.id"
                  :label="item.name"
                  :prop="item.id"
                ></el-table-column>
              </el-table>

              <!-- 多选 -->
              <el-table
                v-if="vlistEntity.vlistType=='0' && vlistEntity.vlistMode=='1'"
                ref="vlistTable01"
                highlight-current-row
                stripe
                :data="tableData.filter(data => !vlistQueryCondtion || data[this.tableColumn[0].id].toLowerCase().includes(vlistQueryCondtion.toLowerCase()))"
                border
                tooltip-effect="dark"
                height="250"
                style="width: 100%"
                v-loading="loading"
                element-loading-text="拼命加载中"
                element-loading-spinner="el-icon-loading"
                element-loading-background="rgba(0, 0, 0, 0.8)"
                @select="handleSelectionChange"
              >
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column
                  v-for="item in tableColumn"
                  :key="item.id"
                  :label="item.name"
                  :prop="item.id"
                ></el-table-column>
              </el-table>

              <!-- 下拉框 -->
              <!-- <el-select
                v-if="vlistEntity.vlistType=='2'"
                v-model="selectValue"
                @change="selectChange"
              >
                <el-option
                  v-for="item in selectData"
                  :label="item.label"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select> -->

              <!-- 一次性加载树形列表 -->
              <el-tree
                v-if="vlistEntity.vlistType=='1' && treeSetEntity.treesetType == '0'"
                ref="myTree"
                class="filter-tree"
                highlight-current
                :data="treeData"
                :props="treeProps"
                :filter-node-method="filterNode"
                v-loading="loading"
                element-loading-text="拼命加载中"
                element-loading-spinner="el-icon-loading"
                element-loading-background="rgba(0, 0, 0, 0.8)"
                @node-click="handleNodeClick"
                @dblclick.native="dbclick"
              ></el-tree>

              <el-tree
                v-if="vlistEntity.vlistType=='1' && treeSetEntity.treesetType == '1'"
                :props="treeProps" 
                :load="loadNode"
                lazy
                highlight-current
                @node-click="handleNodeClick"
                ref="tree">
              </el-tree>
            </div>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-row>
              <el-col :span="12">
                <el-button type="primary" @click="saveVlist" :plain="true">保存</el-button>
              </el-col>
              <el-col :span="5">
                <el-button @click="displayGrid = false">关闭</el-button>
              </el-col>
            </el-row>
          </span>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  getVlistByKey_Url,
  exeVlistSql_Url,
  exeTreeSetSqlForOne_Url,
  exeTreeSetSqlForAsync_Url,
  getTreeSetByCode_Url
} from "@/config/compentsapi";

export default {
  watch: {
    vlistQueryCondtion(val) {
      this.$refs.myTree.filter(val);
    },
    selectString: function(newVal, oldVal) {
      this.selectValue = newVal;
    },
    queryMap: {
      handler(newValue, oldValue) {
        this.queryEntity = newValue;
        // console.log("===>>>>" +JSON.stringify(this.queryEntity));
        this.getGridList();
      },
      deep: true
      }
  },
  name: "gridInput",
  props: {
    vlistCode: {
      type: String
    },
    queryMap: {
      type: Object
    },
    selectString: {
      type: String
    }
  },
  data() {
    return {
      // 查询实体
      queryEntity: this.queryMap,
      // 值列表实体
      vlistEntity: {},
      //
      grid: "",
      vlistQueryCondtion: "",
      returnEntity: {},
      multipleSelection: [],
      tempName: "",
      code: "",
      // 数据
      displayGrid: false,
      tableData: [],
      tableColumn: [],
      // 树形实体
      treeSetEntity: {},
      // 懒加载
      node: [],
      // 树形结构数据
      treeData: [],
      // 树形结构配置选项
      treeProps: {
        label: "label" /* 指定节点标签为节点对象的某个属性 */,
        children: "children" /* 指定子树为节点对象的某个属性 */,
        isLeaf: "HASCHILDREN"
      },
      // 数据加载状态
      loading: true,
      // 下拉框选中的值
      selectValue: this.selectString,
      // 下拉框显示的数据
      selectData: []
    };
  },
  created() {
    this.getGridList();
  },
  activated() {

  },
  methods: {
    // 封装实体查询%@menuCode%入参方法
    // getExecSqlCondition(map) {
    //   var str = this.vlistEntity.vlistSql;
    //   var reg = /\@(.*?)\%/g;
    //   var arr = str.match(reg);
    //   var entity = {};
    //   for (var i = 0; i < arr.length; i++) {
    //     var temp = arr[i].substring(1, arr[i].length - 1);
    //     for(var key in map){
    //       if (temp == key) {
    //         entity[temp] = map[key];
    //       } else {
    //         entity[temp] = "";
    //       }
    //     }
    //   }

    //   entity.vlistCode = this.vlistEntity.vlistCode;
    //   return entity;
    // },

    // 获得初始数据的方法
    getGridList() {
      getVlistByKey_Url({
        vlistCode: this.vlistCode
      }).then(res => {
        if (res.data.success) {
          console.log("获取值列表信息====>>>>>"+JSON.stringify(res.data));
          this.vlistEntity = res.data.data;
          if (this.vlistEntity.vlistType == 1) {
            getTreeSetByCode_Url({
              treeSetCode: this.vlistEntity.vlistSql
            }).then(res => {
              if (res.data.success) {
                this.treeSetEntity = res.data.data;
                console.log("获取树形列表信息====>>>>" + JSON.stringify(this.treeSetEntity));
              } else {
                this.$message.error("树形结构实体查询失败：" + res.data.msg);
              }
            });
            // treeSetType：“0”一次性加载树形，“1”表示异步加载
            if (this.treeSetEntity.treesetType != 1) {
              exeTreeSetSqlForOne_Url({
                treesetCode: this.vlistEntity.vlistSql
              }).then(res => {
                this.loading = false;
                console.log("一次加载完毕====>>>" + JSON.stringify(res.data.data));
                this.treeData = res.data.data;
              });
            } else {
              exeTreeSetSqlForAsync_Url({
                treesetCode: this.vlistEntity.vlistSql
              }).then(res => {
                this.loading = false;
                console.log("异步加载===>>>" + JSON.stringify(res.data.data));
                this.treeData = res.data.data;
              });
            }
            
          } else if (this.vlistEntity.vlistType == 2) {
            this.queryEntity.vlistCode = this.vlistCode;
            exeVlistSql_Url(this.queryEntity).then(res => {
              // console.log("下拉框测试=====>>>>>>" + JSON.stringify(res.data.data.data));
              this.selectData = res.data.data.data;
              var selectedWorkName = "";
              selectedWorkName = this.selectData.find(item => {
                return item.id === this.selectString;
              });
              if (selectedWorkName != null) {
                // console.log(1);
                this.tempName = selectedWorkName.label;
                this.grid = selectedWorkName.label;
              } else {
                // console.log(2);
                this.tempName = "";
                this.grid = "";
              }
            });
          } else {
            // var entity = this.getExecSqlCondition(this.map);
            this.queryEntity.vlistCode = this.vlistCode;
            exeVlistSql_Url(this.queryEntity).then(res => {
              this.loading = false;
              this.tableData = res.data.data.data;
              this.tableColumn = res.data.data.column;
              this.toggleSelection(this.multipleSelection);
            });
          }
        } else {
          this.$message.error("查询失败：" + res.data.msg);
        }
      });
    },

    // 输入框结尾按钮事件
    queryClick() {
      this.getGridList();
      this.displayGrid = !this.displayGrid;
    },

    // 单选行点击事件
    handleRowClick(row) {
      // console.log(JSON.stringify(row)+ "///" + this.tableColumn[0].id + "///" + row[this.tableColumn[0].id]);
      this.returnEntity = row;
      this.tempName = row[this.tableColumn[0].id];
      this.grid = this.tempName;
      this.code = row.code;
      // this.returnValue();
    },

    // 多选框
    handleSelectionChange(val) {
      this.multipleSelection = val;
      // console.log("修改前===>>>" + this.tableColumn[0].id);
      var arr = [];
      for (var i = 0; i < val.length; i++) {
        arr.push(val[i][this.tableColumn[0].id]);
      }
      this.tempName = arr + "";
      // console.log("修改后===>>>" + this.tempName);
    },

    // 选中方法
    toggleSelection(rows) {
      //   this.$refs.vlistTable01.toggleAllSelection();
      if (rows) {
        rows.forEach(row => {
          this.$refs.vlistTable01.toggleRowSelection(row, true);
        });
      } else {
        this.$refs.vlistTable01.clearSelection();
      }
    },

    // 下拉框
    selectChange(vals) {
      // console.log("下拉框选中====>>>>" + vals+"///" + this.selectString);
      // this.selectValue = vals;
      var selectedWorkName = "";
      selectedWorkName = this.selectData.find(item => {
        return item.id === vals;
      });
      if (selectedWorkName != null) {
        // console.log(1);
        this.tempName = selectedWorkName.label;
        this.grid = selectedWorkName.label;
      } else {
        // console.log(2);
        this.tempName = "";
        this.grid = "";
      }
      this.$emit("gridinput", this.selectValue);
    },

    // 树形节点点击事件
    handleNodeClick(data) {
      // console.log("树形点击事件====>>>>" + JSON.stringify(data));
      this.tempName = data.label;
      this.grid = this.tempName;
      this.returnEntity = data;
    },

    // 树形节点双击事件
    dbclick() {
      console.log("双击事件被触发！！！");
    },

    // 树形过滤
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },

    // 树形懒加载问题
    loadNode(node, resolve) {
      if (node.level === 0) {
        this.node = node;
        this.resolve = resolve;
        exeTreeSetSqlForAsync_Url({
          treesetCode: this.vlistEntity.vlistSql,
          treeId: ""
        }).then(res => {
          this.loading = false;
          this.treeData = res.data.data;
          var len = this.treeData.length;
          for (var i = 0; i < len; i++) {
            if (this.treeData[i].HASCHILDREN == "1") {
              this.treeData[i].HASCHILDREN = false;
            } else {
              this.treeData[i].HASCHILDREN = true;
            }
          }
          resolve(this.treeData);
        });
      } else {
        exeTreeSetSqlForAsync_Url({
          treesetCode: this.vlistEntity.vlistSql,
          treeId: node.data.ID
        }).then(res => {
          this.loading = false;
          this.treeData = res.data.data;
          var len = this.treeData.length;
          for (var i = 0; i < len; i++) {
            if (this.treeData[i].HASCHILDREN == "1") {
              this.treeData[i].HASCHILDREN = false;
            } else {
              this.treeData[i].HASCHILDREN = true;
            }
          }
          resolve(this.treeData);
        });
      }
    },

    // 保存按钮
    saveVlist() {
      this.grid = this.tempName;
      this.displayGrid = false;
      this.returnValue();
    },

    // 二次过滤
    queryListData() {},

    // 监听dialog输入框的值做查询
    // getVlistData(vals) {
    //   //["@menuName=111,","@menuCode=111,"]==["@menuName=","@menuCode="]==["=111,","=111,"]
    //   // 全部参数
    //   var reg = /\@(.*?)\,/g;
    //   var arr = [];
    //   if (vals.match(reg) != null) {
    //     arr = vals.match(reg);
    //   }
    //   var mapEntity = {};
    //   for (var i = 0; i < arr.length; i++) {
    //     var key = arr[i].substring(1, arr[i].indexOf("="));
    //     var value = arr[i].substring(arr[i].indexOf("=") + 1, arr[i].indexOf(","));
    //     mapEntity[key] = value;
    //   }
    //   console.log("查询框的值改变===>>>>" + vals);
    //   console.log(Object.keys(mapEntity));
    //   if (Object.keys(mapEntity).length != 0) {
    //     var entity = this.getExecSqlCondition(mapEntity);
    //     console.log("====>>>>>>" + JSON.stringify(entity));
    //     exeVlistSql_Url(entity).then(res => {
    //       console.log("数据======>>>" + JSON.stringify(res.data.data));
    //       this.tableData = res.data.data.data;
    //       this.tableColumn = res.data.data.column;
    //       this.toggleSelection(this.multipleSelection);
    //     });
    //   }
    // },

    // 返回给父组件的方法
    returnValue() {
      if (this.vlistEntity.vlistType == 1) {
        this.$emit("gridinput", this.returnEntity);
      } else {
        if (this.vlistEntity.outputMode == 0) {
          this.$emit("gridinput", this.grid);
        } else if (this.vlistEntity.outputMode == 1) {
          var outKey = this.code;
          var outDescription = this.returnEntity;
          var returnData = {};
          returnData.outKey = outKey;
          returnData.outDescription = outDescription;
          this.$emit("gridinput", returnData);
        } else if (this.vlistEntity.outputMode == 2) {
          this.$emit("gridinput", this.multipleSelection);
        } else if (this.vlistEntity.outputMode == 3) {
          this.$emit("gridinput", this.multipleSelection);
        }
      }
    }
  }
};
</script>
<style>
.grid-list {
  min-width: 623.703px;
  margin-top: 5px;
  background: #ffffff;
  border-radius: 4px;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.05);
}
.vlist-dialog {
  margin-top: 5px;
}
/* .el-table--striped .el-table__body tr.el-table__row--striped td {
  background-color: #e0e0e0;
} */
</style>
